<script lang="ts" setup>
import { useUserStore } from '@/store/user'
import { baseURL } from '@/utils/request'
import { io, type Socket } from '@hyoga/uni-socket.io'
import RoomStatus from './components/room-status.vue'
import { getPatientConsultOrderDetailAPI } from '@/api/consult'
import type { GetPatientConsultOrderDetailRes } from '@/types/consult'
import { nextTick, ref } from 'vue'
import type { ChatMsgListData, MsgItem } from '@/types/room'
import NotifyInfo from './components/notify-info.vue'
import PatientInfo from './components/patient-info.vue'
import MessageInfo from './components/message-info.vue'
import PrescriptionInfo from './components/prescription-info.vue'
import RateInfo from './components/rate-info.vue'
import { uploadFileAPI } from '@/api/common'

// 接收组件外部传入的数据
const props = defineProps<{
  orderId: string
  payResult: 'true' | 'false'
  type: string
}>()

// 获取用户信息
const store = useUserStore()

// 创建socket连接
const socket: Socket = io(baseURL, {
  transports: ['websocket', 'polling'],
  timeout: 5000,
  auth: { token: `Bearer ${store.token}` },
  query: { orderId: props.orderId },
})

// 连接成功
socket.on('connect', () => {
  console.log('连接成功')
})

// 状态改变
socket.on('statusChange', (data) => {
  console.log('状态改变', data)
  getOrderDetail()
})

// 出现错误
socket.on('error', () => {
  console.log('出现错误')
})

// 断开连接
socket.on('disconnect', () => {
  console.log('断开连接')
})

// 查询订单详情信息
const orderDetail = ref<GetPatientConsultOrderDetailRes>()
const getOrderDetail = async () => {
  const res = await getPatientConsultOrderDetailAPI({ orderId: props.orderId })
  orderDetail.value = res
  console.log(orderDetail.value)
}
getOrderDetail()

// 历史消息
const msgList = ref<MsgItem[]>([])
// 历史消息，事件名称为 chatMsgList
socket.on('chatMsgList', (res: ChatMsgListData) => {
  // 业务状态码
  if (res.code !== 10000) return
  // 循环消息组（消息组按时间节点划分，一个消息组包含多个消息）
  res.data?.forEach((item) => {
    // 如果有消息列表，则追加到数组中
    if (item.items) {
      // 时间组
      msgList.value.push({
        createTime: item.createTime,
        msgType: 31,
        msg: {
          content: item.createTime,
        },
      })
      msgList.value.push(...item.items)
    }
  })
})

// 接收医生消息
socket.on('receiveChatMsg', (message: MsgItem) => {
  console.log('医生消息', message)
  socket.emit('updateMsgStatus', message.id)
  // 接收到的消息追加到消息列表中
  msgList.value.push(message)
  // 滚动到底部
  nextTick(() => {
    scrollID.value = `id-${message.id}`
  })
})

// 评价医生

// 发送消息
const textMessage = ref('')
const sendMsg = () => {
  console.log('发送消息', textMessage.value)
  socket.emit('sendChatMsg', {
    from: store.userInfo?.id,
    to: orderDetail.value?.docInfo?.id,
    msgType: 1,
    msg: {
      content: textMessage.value,
    },
  })
  textMessage.value = ''
}

// 发送图片
const sendImage = async () => {
  console.log('发送图片')
  // 如果不是咨询状态，则不能发送图片
  if (orderDetail.value?.status !== 3) {
    uni.showToast({
      title: '当前状态不能发送图片',
      icon: 'none',
    })
    return
  }
  // 调用选择图片的api
  const { tempFilePaths } = await uni.chooseImage({
    // 最多选择一张图片
    count: 1,
    // 原图和压缩图
    sizeType: ['original', 'compressed'],
    // 相册和相机
    sourceType: ['album', 'camera'],
  })
  // 上传图片
  const res = await uploadFileAPI(tempFilePaths[0])
  console.log(res)
  // 发送图片
  socket.emit('sendChatMsg', {
    // 发送者id
    from: store.userInfo?.id,
    // 接收者id
    to: orderDetail.value?.docInfo?.id,
    // 消息类型 4图片
    msgType: 4,
    // 消息内容
    msg: {
      // 图片信息
      picture: { ...res },
    },
  })
}

// 滚动到底部
const scrollID = ref<string>()
</script>

<template>
  <RoomStatus
    v-if="orderDetail"
    :status="orderDetail?.status"
    :statusValue="orderDetail?.statusValue"
    :countdown="orderDetail?.countdown"
  />
  <view class="room-page">
    <scroll-view
      refresher-enabled
      refresher-background="#f2f2f2"
      scroll-y
      style="flex: 1; overflow: hidden"
      :scroll-into-view="scrollID"
    >
      <view class="message-container">
        <!-- 此处将来填充更多代码... -->
        <!-- 消息的类型1文字
21卡片-患者病情 22卡片-处方信息 23未提交评价24已提交评价
31通知-普通通知（白底黑色）32通知-温馨提示33通知-订单取消（灰色底黑字）4图片 -->
        <view v-for="(item, index) in msgList" :key="index" class="message-item" :id="`id-${item.id}`">
          <PatientInfo v-if="item.msgType === 21" :info="item.msg?.consultRecord" />
          <NotifyInfo v-else-if="item.msgType && item.msgType >= 31" :type="item.msgType">
            {{ item.msg?.content }}
          </NotifyInfo>
          <MessageInfo v-else-if="item.msgType === 1 || item.msgType === 4" :message="item" />
          <PrescriptionInfo v-else-if="item.msgType === 22" :info="item.msg?.prescription!" />
          <RateInfo
            v-else-if="item.msgType === 23"
            :orderId="orderId"
            :doctorId="orderDetail?.docInfo?.id"
          />
        </view>
      </view>
    </scroll-view>

    <!-- 发送消息 -->
    <view class="message-bar">
      <template v-if="true">
        <uni-easyinput
          :disabled="orderDetail?.status !== 3"
          :clearable="false"
          :input-border="false"
          placeholder-style="font-size: 32rpx; color: #c3c3c5;"
          placeholder="问医生"
          v-model="textMessage"
          @confirm="sendMsg"
        />
        <view class="image-button" @click="sendImage">
          <uni-icons size="40" color="#979797" type="image"></uni-icons>
        </view>
      </template>
      <button v-else class="uni-button">咨询其它医生</button>
    </view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
